import { ADDGOODS,DELETEGOODS,INCREASE,REDUCER } from '../constants'

const initState={
    goods:{
        list:[]
    },
    price:0
}

function cart(state=initState,action){
    switch(action.type){
        case ADDGOODS:
        if(state.goods.list.length===0){
            console.log(action.data)
            return{
                ...state,
                goods:{
                    list:[action.data]
                }
            }
        }else{
            var listname=[]
            for(var i in state.goods.list){
                listname.push(state.goods.list[i].name)
            }
            if(listname.includes(action.data.name)){
                for(var i in state.goods.list){
                    if(state.goods.list[i].name===action.data.name){
                        state.goods.list[i].num+=1;
                    }
                }
                var list=state.goods.list;
                return{
                    ...state,
                    goods:{
                        list:list
                    }
                
                }
            }else{
                return {
                    ...state,
                    goods:{
                        list:[...state.goods.list,action.data]
                    }
                }
            }
        }
        case DELETEGOODS:
        var index=0,isexcit=false;
        if(state.goods.list.length>0){
            for(var i in state.goods.list){
                if(action.data.name===state.goods.list[i].name){
                    index=i;
                    isexcit=true;
                }
            }
            if(state.goods.list[index].num>1){
                state.goods.list[index].num=state.goods.list[index].num-1
                var list=state.goods.list;
                return{
                    ...state,
                    goods:{
                        list:list
                    }
                }
            }else{
                if(isexcit){
                    state.goods.list.splice(index,1)
                    return {
                    ...state,
                    goods:{
                            list:state.goods.list
                        }
                    }
                }else{
                    return{
                        ...state
                    }
                }
                    
                }
        }else{
            return{
                ...state  
            }
        }
        default:
        return state
    }
}



export default cart